﻿/********************************************************
 * Project Name   : VAdvantage
 * Class Name     : InfoProduct
 * Purpose        : To search the product Under c_product
 * Class Used     : Info
 * Chronological    Development
 * Raghunandan     10-Dec=2010
  ******************************************************/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
//using System.Collections;
using System.Collections.Generic;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using System.Windows.Forms;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Framework;
using VAdvantage.Logging;
using System.Linq;
using System.Windows.Media.Imaging;

namespace VAdvantage.Search
{
    public class InfoProduct : Info
    {
        #region Private Variable
        //	Logger			
        private static VLogger _log = VLogger.GetVLogger(typeof(InfoProduct));
        // Array of Column Info    
        private static Info_Column[] s_productLayout = null;
        private static int INDEX_NAME = 0;
        private static int INDEX_PATTRIBUTE = 0;
        // Header for Price List Version 	
        private static String s_headerPriceList = "";
        // Header for Warehouse 		
        private static String s_headerWarehouse = "";
        // ASI						
        private int _M_AttributeSetInstance_ID = -1;
        // Locator						
        private int _M_Locator_ID = 0;
        // Display Price List Column
        private bool _displayPriceList = false;
        // Display Warehouse Column	
        private bool _displayWarehouse = false;
        // Security for Price List Version 	
        private String _securityPriceList = null;
        // Security for Warehouse 	
        private String _securityWarehouse = null;
        private String _pAttributeWhere = null;
        private int _C_BPartner_ID = 0;

        private const int HEIGHT = 23;
        private VLabel lblValue = new VLabel();
        private VTextBox txtValue = new VTextBox(HEIGHT);

        private VLabel lblName = new VLabel();
        private VTextBox txtName = new VTextBox(HEIGHT);
        private VLabel lblUPC = new VLabel();
        private VTextBox txtUPC = new VTextBox(HEIGHT);
        private VLabel lblSKU = new VLabel();
        private VTextBox txtSKU = new VTextBox(HEIGHT);
        private VLabel lblPriceList = new VLabel();
        private VComboBox cmbPickPriceList = new VComboBox();
        private VLabel lblWarehouse = new VLabel();
        private VComboBox cmbPickWarehouse = new VComboBox();
        //	Search Button				
        private VButton btnInfoPAttributeButton = new VButton();
        //Instance Button			
        private VButton btnPAttributeButton = new VButton();
        //ImageButton bRefresh1 = ConfirmPanel.CreateRefreshButton(true);

        #endregion

        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="frame">frame</param>
        /// <param name="modal">modal</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="M_Warehouse_ID">warehouse</param>
        /// <param name="M_PriceList_ID">price list</param>
        /// <param name="value">Query Value or Name if enclosed in @</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="whereClause">where clause</param>
        public InfoProduct(Object frame, bool modal, int WindowNo, int M_Warehouse_ID, int M_PriceList_ID, String value,
            bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "p", "M_Product_ID", multiSelection, whereClause)
        {
            btnInfoPAttributeButton.Visible = true;
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoProduct", true));
            StatInit();
            InitInfo(value, M_Warehouse_ID, M_PriceList_ID);
            _C_BPartner_ID = Envs.GetContext().GetContextAsInt(WindowNo, "C_BPartner_ID");

            //int no = vdgvRecords.RowCount;
            var count = 0;
            if (vdgvRecords.ItemsSource != null)
            {
                //IEnumerable<Object>[] _lst = vdgvRecords.ItemsSource;
                //no = _lst.Length;
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }

            base.SetStatusMsg(count.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            //	AutoQuery
            if (value != null && value.Length > 0)
            {
                cmblisObj = cmbPickPriceList.SelectedItem;
                cmbwerobj = cmbPickWarehouse.SelectedItem;
                ExecuteQuery();
            }
            _LoadedOK = true;
            //	Focus
            txtValue.Focus();
        }

        //SQL From				
        private static String s_productFrom =
            "M_Product p"
            + " LEFT OUTER JOIN M_ProductPrice pr ON (p.M_Product_ID=pr.M_Product_ID AND pr.IsActive='Y')"
            + " LEFT OUTER JOIN M_PriceList_Version plv ON (pr.M_PriceList_Version_ID=plv.M_PriceList_Version_ID)"
            + " LEFT OUTER JOIN M_AttributeSet pa ON (p.M_AttributeSet_ID=pa.M_AttributeSet_ID),"
            + " M_Warehouse w";

        /// <summary>
        /// Static Setup - add fields to parameterPanel
        /// </summary>
        private void StatInit()
        {
            InfoSetting();
            lblValue.Content = Msg.GetMsg(Envs.GetCtx(), "Value");
            //lblValue.AutoSize = true;
            lblName.Content = Msg.GetMsg(Envs.GetCtx(), "Name");
            //lblName.AutoSize = true;
            lblUPC.Content = Msg.GetMsg(Envs.GetCtx(), "UPC");
            //lblUPC.AutoSize = true;
            lblSKU.Content = Msg.GetMsg(Envs.GetCtx(), "SKU");
            //lblSKU.AutoSize = true;
            lblWarehouse.Content = Msg.GetMsg(Envs.GetCtx(), "Warehouse");
            // lblWarehouse.AutoSize = true;
            lblPriceList.Content = Msg.GetMsg(Envs.GetCtx(), "PriceListVersion");
            //lblPriceList.AutoSize = true;

            //Level Controls alignment
            lblValue.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblValue.Margin = new Thickness(5, 5, 5, 5);

            lblName.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblName.Margin = new Thickness(5, 5, 5, 5);

            lblUPC.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblUPC.Margin = new Thickness(5, 5, 5, 5);

            lblSKU.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblSKU.Margin = new Thickness(5, 5, 5, 5);

            lblWarehouse.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblWarehouse.Margin = new Thickness(5, 5, 5, 5);

            lblPriceList.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblPriceList.Margin = new Thickness(5, 5, 5, 5);

            //textbox controls alignment
            txtValue.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            txtValue.Margin = new Thickness(5, 5, 5, 5);


            txtName.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            txtName.Margin = new Thickness(5, 5, 5, 5);

            txtSKU.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            txtSKU.Margin = new Thickness(5, 5, 5, 5);

            txtUPC.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            txtUPC.Margin = new Thickness(5, 5, 5, 5);

            cmbPickPriceList.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cmbPickPriceList.Margin = new Thickness(5, 5, 5, 5);

            cmbPickWarehouse.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cmbPickWarehouse.Margin = new Thickness(5, 5, 5, 5);

            txtName.Width = 130;
            txtSKU.Width = 130;
            txtUPC.Width = 130;
            txtValue.Width = 130;
            cmbPickWarehouse.Width = 130;
            cmbPickPriceList.Width = 130;

            //Now Add controls in the grid
            //value
            Grid.SetRow(lblValue, 0);
            Grid.SetColumn(lblValue, 0);
            this.tablePanel.Children.Add(lblValue);

            Grid.SetRow(txtValue, 0);
            Grid.SetColumn(txtValue, 1);
            this.tablePanel.Children.Add(txtValue);


            //Upc
            Grid.SetRow(lblUPC, 0);
            Grid.SetColumn(lblUPC, 2);
            this.tablePanel.Children.Add(lblUPC);

            Grid.SetRow(txtUPC, 0);
            Grid.SetColumn(txtUPC, 3);
            this.tablePanel.Children.Add(txtUPC);

            //wherehouse
            Grid.SetRow(lblWarehouse, 0);
            Grid.SetColumn(lblWarehouse, 4);
            this.tablePanel.Children.Add(lblWarehouse);

            Grid.SetRow(cmbPickWarehouse, 0);
            Grid.SetColumn(cmbPickWarehouse, 5);
            this.tablePanel.Children.Add(cmbPickWarehouse);

            //Name
            Grid.SetRow(lblName, 1);
            Grid.SetColumn(lblName, 0);
            this.tablePanel.Children.Add(lblName);

            Grid.SetRow(txtName, 1);
            Grid.SetColumn(txtName, 1);
            this.tablePanel.Children.Add(txtName);

            //Sku
            Grid.SetRow(lblSKU, 1);
            Grid.SetColumn(lblSKU, 2);
            this.tablePanel.Children.Add(lblSKU);

            Grid.SetRow(txtSKU, 1);
            Grid.SetColumn(txtSKU, 3);
            this.tablePanel.Children.Add(txtSKU);

            //price
            Grid.SetRow(lblPriceList, 1);
            Grid.SetColumn(lblPriceList, 4);
            this.tablePanel.Children.Add(lblPriceList);

            Grid.SetRow(cmbPickPriceList, 1);
            Grid.SetColumn(cmbPickPriceList, 5);
            this.tablePanel.Children.Add(cmbPickPriceList);

            //Product Attribute Instance--Here we haven't give btnPAttributeButton Functionality 
            //btnInfoPAttributeButton.AutoSize = true;
            Image myImage = new Image();
            myImage.Source = Envs.LoadImageSource("PAttribute16.png");
            btnInfoPAttributeButton.Content = myImage;// global::VAdvantage.Resources.PrintScreen16;
            btnInfoPAttributeButton.Width = 50;

            Grid.SetRow(btnInfoPAttributeButton, 0);
            Grid.SetColumn(btnInfoPAttributeButton, 6);
            this.tablePanel.Children.Add(btnInfoPAttributeButton);


            //	Product Attribute Instance
            btnPAttributeButton.IsEnabled = false;
            btnPAttributeButton.Visible = false;

            btnInfoPAttributeButton.Click += new RoutedEventHandler(btnInfoPAttributeButton_Click);
            btnPAttributeButton.Click += new RoutedEventHandler(btnPAttributeButton_Click);
            txtValue.KeyDown += new KeyEventHandler(KeyEvents);
            txtName.KeyDown += new KeyEventHandler(KeyEvents);
            txtSKU.KeyDown += new KeyEventHandler(KeyEvents);
            txtUPC.KeyDown += new KeyEventHandler(KeyEvents);
            vdgvRecords.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords_AutoGeneratingColumn);
        }

        protected void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(35, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            //parameter panel   
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }

        /// <summary>
        ///Dynamic Init
        /// </summary>
        /// <param name="value">value</param>
        /// <param name="M_Warehouse_ID">warehouse</param>
        /// <param name="M_PriceList_ID">price list</param>
        private void InitInfo(String value, int M_Warehouse_ID, int M_PriceList_ID)
        {
            //	Pick init
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                Utility.Envs.SetThreadCulture();

                FillPicks(M_PriceList_ID);
                int M_PriceList_Version_ID = FindPLV(Envs.GetContext(), _WindowNo, M_PriceList_ID);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(priceListVersions, warehouses, M_PriceList_Version_ID, value, M_Warehouse_ID, M_PriceList_ID));
            });

        }
        private void InvoKFunction(List<KeyNamePair> priceListVersions, List<KeyNamePair> warehouses, int M_PriceList_Version_ID, String value, int M_Warehouse_ID, int M_PriceList_ID)
        {

            StringBuilder security = new StringBuilder();
            security = new StringBuilder();
            cmbPickPriceList.Items.Add(new KeyNamePair(0, ""));
            //for( KeyNamePair pair : priceListVersions )
            foreach (KeyNamePair pair in priceListVersions)
            {
                if (security.Length > 0)
                    security.Append(",");
                security.Append(pair.GetKey());
                cmbPickPriceList.Items.Add(pair);
            }
            _securityPriceList = " AND plv.M_PriceList_Version_ID IN (" + security.ToString() + ")";

            security = new StringBuilder();
            cmbPickWarehouse.Items.Add(new KeyNamePair(0, ""));
            //for( KeyNamePair pair : warehouses )
            foreach (KeyNamePair pair in warehouses)
            {
                if (security.Length > 0)
                    security.Append(",");
                security.Append(pair.GetKey());
                cmbPickWarehouse.Items.Add(pair);
            }
            //_securityWarehouse = " AND w.M_Warehouse_ID IN (" + security.ToString() + ")";
            _securityWarehouse = " AND w.M_Warehouse_ID IN (" + security.ToString() + ")";


            //	Set Value or Name
            if (value.StartsWith("@") && value.EndsWith("@"))
            {
                txtName.Text = value.Substring(1, value.Length - 2);
            }
            else
            {
                txtName.Text = value;
            }

            //	Set Warehouse
            if (M_Warehouse_ID == 0)
                M_Warehouse_ID = Envs.GetContext().GetContextAsInt("#M_Warehouse_ID");
            if (M_Warehouse_ID != 0)
            {
                SetWarehouse(M_Warehouse_ID);
            }
            // 	Set PriceList Version
            if (M_PriceList_Version_ID != 0)
            {
                SetPriceListVersion(M_PriceList_Version_ID);
            }
            //	Create Grid
            StringBuilder where = new StringBuilder();
            where.Append("p.IsActive='Y'");
            if (M_Warehouse_ID != 0)
                where.Append(" AND p.IsSummary='N'");
            //  dynamic Where Clause
            if (_whereClause != null && _whereClause.Length > 0)
            {
                where.Append(" AND ")   //  replace fully qalified name with alias
                    .Append(Util.Replace(_whereClause, "M_Product.", "p."));
            }
            PrepareTable(s_productFrom, where.ToString(), "QtyAvailable DESC, Margin DESC");
            SetBusy(false);
        }

        public static List<KeyNamePair> GetPriceListVersions(int M_PriceList_ID)
        {
            List<KeyNamePair> result = new List<KeyNamePair>();

            String SQL = "SELECT M_PriceList_Version.M_PriceList_Version_ID,"
                    + " M_PriceList_Version.Name || ' (' || c.ISO_Code || ')' AS ValueName "
                    + "FROM M_PriceList_Version, M_PriceList pl, C_Currency c "
                    + "WHERE M_PriceList_Version.M_PriceList_ID=pl.M_PriceList_ID" + " AND pl.C_Currency_ID=c.C_Currency_ID"
                    + " AND M_PriceList_Version.IsActive='Y' AND pl.IsActive='Y'";
            // Same PL currency as original one
            if (M_PriceList_ID != 0)
            {
                SQL += " AND EXISTS (SELECT * FROM M_PriceList xp WHERE xp.M_PriceList_ID=" + M_PriceList_ID + ")";
                //   +" AND pl.C_Currency_ID=xp.C_Currency_ID)";
            }
            // Add Access & Order
            SQL = MRole.GetDefault().AddAccessSQL(SQL, "M_PriceList_Version", true, false) // fully
                // qualidfied
                // - RO
                    + " ORDER BY M_PriceList_Version.Name";

            StringBuilder security = new StringBuilder();
            DataSet ds = null;
            ds = VAdvantage.DataBase.DB.ExecuteDataset(SQL, null);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow dr = ds.Tables[0].Rows[i];
                int M_PriceList_Version_ID = int.Parse(dr[0].ToString());
                if (security.Length > 0)
                {
                    security.Append(",");
                }
                security.Append(M_PriceList_Version_ID);
                KeyNamePair kn = new KeyNamePair(M_PriceList_Version_ID, dr[1].ToString());
                result.Add(kn);
            }
            return result;
        }

        public static List<KeyNamePair> GetWarehouses()
        {
            List<KeyNamePair> result = new List<KeyNamePair>();

            // Warehouse
            String SQL = MRole.GetDefault().AddAccessSQL(
                    "SELECT M_Warehouse_ID, Value || ' - ' || Name AS ValueName " + "FROM M_Warehouse " + "WHERE IsActive='Y'",
                    "M_Warehouse", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO)
                    + " ORDER BY Value";
            DataSet ds = null;
            ds = VAdvantage.DataBase.DB.ExecuteDataset(SQL, null);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow dr = ds.Tables[0].Rows[i];
                int M_Warehouse_ID = Convert.ToInt32(dr[0]);// int.Parse(dr[0].ToString());
                KeyNamePair kn = new KeyNamePair(M_Warehouse_ID, dr[1].ToString());
                result.Add(kn);
            }
            return result;
        }

        /// <summary>
        /// Fill Picks with values
        /// </summary>
        /// <param name="M_PriceList_ID">M_PriceList_ID price list</param>
        //private void FillPicks(int M_PriceList_ID)
        //{
        //    StringBuilder security = new StringBuilder();
        //    List<KeyNamePair> priceListVersions = new List<KeyNamePair>();
        //    try
        //    {
        //        priceListVersions = GetPriceListVersions(M_PriceList_ID);
        //    }
        //    catch (Exception e)
        //    {
        //        SetStatusMsg(e.Message);
        //    }
        //    security = new StringBuilder();
        //    cmbPickPriceList.Items.Add(new KeyNamePair(0, ""));
        //    //for( KeyNamePair pair : priceListVersions )
        //    foreach (KeyNamePair pair in priceListVersions)
        //    {
        //        if (security.Length > 0)
        //            security.Append(",");
        //        security.Append(pair.GetKey());
        //        cmbPickPriceList.Items.Add(pair);
        //    }
        //    _securityPriceList = " AND plv.M_PriceList_Version_ID IN (" + security.ToString() + ")";
        //    List<KeyNamePair> warehouses = new List<KeyNamePair>();
        //    try
        //    {
        //        warehouses = GetWarehouses();
        //    }
        //    catch (Exception e)
        //    {
        //        SetStatusMsg(e.Message);
        //    }

        //    security = new StringBuilder();
        //    cmbPickWarehouse.Items.Add(new KeyNamePair(0, ""));
        //    //for( KeyNamePair pair : warehouses )
        //    foreach (KeyNamePair pair in warehouses)
        //    {
        //        if (security.Length > 0)
        //            security.Append(",");
        //        security.Append(pair.GetKey());
        //        cmbPickWarehouse.Items.Add(pair);
        //    }
        //    //_securityWarehouse = " AND w.M_Warehouse_ID IN (" + security.ToString() + ")";
        //    _securityWarehouse = " AND w.M_Warehouse_ID IN (" + security.ToString() + ")";

        //}

        List<KeyNamePair> priceListVersions = new List<KeyNamePair>();
        List<KeyNamePair> warehouses = new List<KeyNamePair>();
        bool isConferm = false; //IsUnconfirmed())
        private void FillPicks(int M_PriceList_ID)
        {
            try
            {
                priceListVersions = GetPriceListVersions(M_PriceList_ID);
                warehouses = GetWarehouses();
                isConferm = IsUnconfirmed();
            }
            catch (Exception e)
            {
                SetStatusMsg(e.Message);
            }
        }
        /// <summary>
        /// Set Warehouse
        /// </summary>
        /// <param name="M_Warehouse_ID">warehouse</param>
        private void SetWarehouse(int M_Warehouse_ID)
        {
            for (int i = 0; i < cmbPickWarehouse.Items.Count; i++)
            {
                KeyNamePair kn = (KeyNamePair)cmbPickWarehouse.Items[i];
                if (kn.GetKey() == M_Warehouse_ID)
                {
                    //cmbPickWarehouse.setSelectedIndex(i);
                    cmbPickWarehouse.SelectedIndex = i;
                    return;
                }
            }
        }

        /// <summary>
        /// Set PriceList
        /// </summary>
        /// <param name="M_PriceList_Version_ID">price list</param>
        private void SetPriceListVersion(int M_PriceList_Version_ID)
        {
            log.Config("M_PriceList_Version_ID=" + M_PriceList_Version_ID);
            for (int i = 0; i < cmbPickPriceList.Items.Count; i++)
            {
                KeyNamePair kn = (KeyNamePair)cmbPickPriceList.Items[i];
                if (kn.GetKey() == M_PriceList_Version_ID)
                {
                    //cmbpickPriceList.setSelectedIndex(i);
                    cmbPickPriceList.SelectedIndex = i;
                    return;
                }
            }
            //log.fine("NOT found");
        }

        /// <summary>
        /// Find Price List Version and update context
        /// </summary>
        /// <param name="ctx">Context</param>
        /// <param name="p_WindowNo">window no</param>
        /// <param name="M_PriceList_ID">price list</param>
        /// <returns>M_PriceList_Version_ID price list version</returns>
        public static int FindPLV(Context ctx, int p_WindowNo, int M_PriceList_ID)
        {
            DateTime priceDate = new DateTime();
            //	Sales Order Date
            String dateStr = ctx.GetContext(p_WindowNo, "DateOrdered");
            //String dateStr =CommonFunctions.CovertMilliToDate(ctx.GetContextAsTime(p_WindowNo, "DateOrdered")).ToString();
            if (dateStr != null && dateStr.Length > 0)
                priceDate = System.Convert.ToDateTime(Envs.GetContext().GetContext(p_WindowNo, "DateOrdered", false));
            else	//	Invoice Date
            {
                dateStr = ctx.GetContext(p_WindowNo, "DateInvoiced");
                if (dateStr != null && dateStr.Length > 0)
                    priceDate = System.Convert.ToDateTime(Envs.GetContext().GetContext(p_WindowNo, "DateInvoiced", false));
            }
            //	Today 
            if (priceDate == null)
                priceDate = System.Convert.ToDateTime(DateTime.Now);
            //
            //_log.config("M_PriceList_ID=" + M_PriceList_ID + " - " + priceDate);
            int retValue = 0;
            String sql = "SELECT plv.M_PriceList_Version_ID, plv.ValidFrom "
                + "FROM M_PriceList pl, M_PriceList_Version plv "
                + "WHERE pl.M_PriceList_ID=plv.M_PriceList_ID"
                + " AND plv.IsActive='Y'"
                + " AND pl.M_PriceList_ID=" + M_PriceList_ID					//	1
                + " ORDER BY plv.ValidFrom DESC";
            //	find newest one
            try
            {
                DataSet ds = null;
                ds = VAdvantage.DataBase.DB.ExecuteDataset(sql, null);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    DateTime plDate = Convert.ToDateTime(dr[1]);
                    //if (!priceDate.before(plDate))
                    if (priceDate > plDate)
                    {
                        //get prise
                        retValue = Convert.ToInt32(dr[0]);
                    }
                    else
                    {
                        retValue = Convert.ToInt32(dr[0]);//do not use else this only to show records with where clous
                    }
                }
            }
            catch (Exception e)
            {
                //_log.log(Level.SEVERE, sql, e);
            }
            ctx.SetContext(p_WindowNo, "M_PriceList_Version_ID", retValue.ToString());
            return retValue;
        }

        String value = "";
        String name = "";
        String upc = "";
        String sku = "";

        /// <summary>
        /// Construct SQL Where Clause and define parameters
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>SQL WHERE clause</returns>
        public override String GetSQLWhere()
        {
            StringBuilder where = new StringBuilder();
            try
            {
                //  Optional Warehouse
                int M_Warehouse_ID = 0;
                KeyNamePair wh = new KeyNamePair();
                wh = (KeyNamePair)cmbwerobj;
                if (wh != null)
                {
                    M_Warehouse_ID = wh.GetKey();
                }
                _displayWarehouse = M_Warehouse_ID == 0;
                if (M_Warehouse_ID != 0)
                {
                    where.Append(" AND w.M_Warehouse_ID=" + M_Warehouse_ID);
                }
                else
                {
                    where.Append(_securityWarehouse);
                }
                //	Optional PLV
                int M_PriceList_Version_ID = 0;
                KeyNamePair pl = (KeyNamePair)cmblisObj;
                if (pl != null)
                {
                    M_PriceList_Version_ID = pl.GetKey();
                }
                _displayPriceList = M_PriceList_Version_ID == 0;
                if (M_PriceList_Version_ID != 0)
                {
                    where.Append(" AND pr.M_PriceList_Version_ID=" + M_PriceList_Version_ID);
                }
                else
                {
                    where.Append(_securityPriceList);
                }
                //	Product Attribute Search
                if (_pAttributeWhere != null)
                {
                    where.Append(_pAttributeWhere);
                    return where.ToString();
                }

                //	=> Value

                Dispatcher.BeginInvoke(delegate() { value = txtValue.Text.ToUpper(); });
                if (!(value.Equals("") || value.Equals("%")))
                {
                    if (!value.EndsWith("%"))
                    {
                        value += "%";
                    }
                    if (!value.StartsWith("%"))
                    {
                        value = "%" + value;
                    }
                    where.Append(" AND UPPER(p.Value) LIKE '" + value + "'");
                }

                //  => Name
                //String name = txtName.Text.ToUpper();
                Dispatcher.BeginInvoke(delegate() { name = txtName.Text.ToUpper(); });
                if (!(name.Equals("") || name.Equals("%")))
                {
                    if (!name.EndsWith("%"))
                    {
                        name += "%";
                    }
                    if (!name.StartsWith("%"))
                    {
                        name = "%" + name;
                    }
                    where.Append(" AND UPPER(p.Name) LIKE '" + name + "'");
                }

                //  => UPC
                //String upc = txtUPC.Text.ToUpper();
                Dispatcher.BeginInvoke(delegate() { upc = txtUPC.Text.ToUpper(); });
                if (!(upc.Equals("") || upc.Equals("%")))
                {
                    if (!upc.EndsWith("%"))
                        upc += "%";
                    where.Append(" AND UPPER(p.UPC) LIKE '" + upc + "'");
                }

                //  => SKU
                //String sku = txtSKU.Text.ToUpper();
                Dispatcher.BeginInvoke(delegate() { sku = txtSKU.Text.ToUpper(); });
                if (!(sku.Equals("") || sku.Equals("%")))
                {
                    if (!sku.EndsWith("%"))
                        sku += "%";
                    where.Append(" AND UPPER(p.SKU) LIKE '" + sku + "'");
                }

                //    //	Show/hide columns
                //    int size = vdgvRecords.ItemsSource.OfType<object>().Count();
                //    for (int col = 0; col < size; col++)
                //    {
                //        //TableColumn tc = p_table.getColumnModel().getColumn(col);
                //        Object hv = vdgvRecords.Columns[col].Header;
                //        if ((!_displayPriceList && s_headerPriceList.Equals(hv.ToString()))
                //            || (!_displayWarehouse && s_headerWarehouse.Equals(hv.ToString())))
                //        {
                //            // vdgvRecords.Columns[col].Resizable = false;
                //        }
                //        else
                //        {
                //            // vdgvRecords.Columns[col].Resizable = true;
                //        }
                //    }
            }
            catch { }

            return where.ToString();

        }

        /// <summary>
        ///Set Parameters for Query
        ///(as defined in getSQLWhere)
        /// </summary>
        /// <param name="pstmt">pstmt</param>
        /// <param name="forCount">for counting records only</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            int index = 0;
            //String value = txtValue.Text.ToUpper();
            //String name = txtName.Text.ToUpper();
            //String upc = txtUPC.Text.ToUpper();
            //String sku = txtSKU.Text.ToUpper();

            int M_Warehouse_ID = 0;
            int M_PriceList_Version_ID = 0;
            int paramcount = 0;

            if (!(value.Equals("") || value.Equals("%")))
            {
                //paramcount++;
            }
            if (!(name.Equals("") || name.Equals("%")))
            {
                //paramcount++;
            }
            if (!(upc.Equals("") || upc.Equals("%")))
            {
                //paramcount++;
            }
            if (!(sku.Equals("") || sku.Equals("%")))
            {
                //paramcount++;
            }

            param = new SqlParameter[paramcount];

            //	Rest of Parameter in Query for Attribute Search
            if (_pAttributeWhere != null)
            {
                return;
            }


            //  => Value

            if (!(value.Equals("") || value.Equals("%")))
            {
                if (!value.EndsWith("%"))
                {
                    value += "%";
                }

                // param[index++] = new SqlParameter("@param1", value);
            }


            //  => Name

            if (!(name.Equals("") || name.Equals("%")))
            {
                if (!name.EndsWith("%"))
                {
                    name += "%";
                }
                // param[index++] = new SqlParameter("@param2", name);
            }


            //  => UPC

            if (!(upc.Equals("") || upc.Equals("%")))
            {
                if (!upc.EndsWith("%"))
                    upc += "%";
                // param[index++] = new SqlParameter("@param3", upc);
            }


            //  => SKU

            if (!(sku.Equals("") || sku.Equals("%")))
            {
                if (!sku.EndsWith("%"))
                    sku += "%";
                // param[index++] = new SqlParameter("@param4", sku);
            }
        }

        /// <summary>
        /// button click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPAttributeButton_Click(object sender, RoutedEventArgs e)
        {
            //	Query Product Attribure Instance
            //int row = p_table.getSelectedRow();
            int row = vdgvRecords.ItemsSource.OfType<object>().Count();// SelectedRows.Count;
            //if (e.Equals(btnInfoPAttributeButton) && row != -1)
            //{
            //    int productInteger = int.Parse(GetSelectedRowKey().ToString());
            //    //string productName = (String)p_table.getModel().getValueAt(row, INDEX_NAME);
            //    KeyNamePair warehouse = (KeyNamePair)cmbPickWarehouse.SelectedItem;
            //    if (productInteger == null || productInteger == 0 || warehouse == null)
            //        return;
            //    String title = warehouse.GetName() + " - " + ProductName;
            //    int window_id = warehouse.GetKey();
            //    PAttributeInstance pai = new PAttributeInstance(this, title, window_id, 0, productInteger, _C_BPartner_ID);
            //    _M_AttributeSetInstance_ID = pai.GetM_AttributeSetInstance_ID();
            //    _M_Locator_ID = pai.GetM_Locator_ID();
            //    if (_M_AttributeSetInstance_ID != -1)
            //        Dispose();
            //    return;
            //}
        }
        private void btnInfoPAttributeButton_Click(object sender, RoutedEventArgs e)
        {
            //	Product Attribute Search
            Cmd_InfoPAttribute();
            return;
            //_pAttributeWhere = null;
        }

        /// <summary>
        /// Enable PAttribute if row selected/changed
        /// </summary>
        private void EnableButtons()
        {
            _M_AttributeSetInstance_ID = -1;
            if (btnPAttributeButton != null)
            {
                //int row = p_table.getSelectedRow();
                int row = 0;
                bool enabled = false;
                if (row >= 0)
                {
                    //Object value = p_table.getModel().getValueAt(row, INDEX_PATTRIBUTE);
                    //enabled = Boolean.TRUE.equals(value);
                }
                btnPAttributeButton.IsEnabled = enabled;
            }
            //base.enableButtons();
        }

        /// <summary>
        /// Query per Product Attribute.
        /// <code>
        /// Available synonyms:
        /// M_Product p
        /// M_ProductPrice pr
        /// M_AttributeSet pa
        /// </code>
        /// </summary>
        private void Cmd_InfoPAttribute()
        {
            InfoPAttribute ia = new InfoPAttribute(this);
            //_pAttributeWhere = ia.GetWhereClause();
            //if (_pAttributeWhere != null)
            //{
            //    ExecuteQuery();
            //}
        }

        public void RunAttributeQuery(string query)
        {
            _pAttributeWhere = query;
            if (_pAttributeWhere != null)
            {
                ExecuteQuery();
            }
        }

        /// <summary>
        /// Show History
        /// </summary>
        private void ShowHistory()
        {
            int? M_Product_ID = GetSelectedRowKey();
            if (M_Product_ID == null)
                return;
            KeyNamePair kn = (KeyNamePair)cmbPickWarehouse.SelectedItem;
            int M_Warehouse_ID = kn.GetKey();
            int M_AttributeSetInstance_ID = _M_AttributeSetInstance_ID;
            if (_M_AttributeSetInstance_ID < -1)	//	not selected
                M_AttributeSetInstance_ID = 0;
            // InvoiceHistory ih = new InvoiceHistory(this, 0,M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID);
            //ih.setVisible(true);
            //ih = null;
        }

        /// <summary>
        /// Has History
        /// </summary>
        /// <returns>true (has history)</returns>
        private bool HasHistory()
        {
            return true;
        }

        /// <summary>
        /// Zoom
        /// </summary>
        private void Zoom()
        {
            int? M_Product_ID = GetSelectedRowKey();
            if (M_Product_ID == null)
                return;
            //	AEnv.zoom(MProduct.Table_ID, M_Product_ID.intValue(), true);	//	SO

            Query query = new Query("M_Product");
            query.AddRestriction("M_Product_ID", Query.EQUAL, M_Product_ID);
            query.SetRecordCount(1);
            int AD_WindowNo = GetAD_Window_ID("M_Product", true);	//	SO
            //Zoom(AD_WindowNo, query);
        }

        /// <summary>
        /// *	Has Zoom
        /// </summary>
        /// <returns>(has zoom)</returns>
        private bool HasZoom()
        {
            return true;
        }

        /// <summary>
        /// Customize
        /// </summary>
        void Customize()
        {
            log.Info("");
        }

        /// <summary>
        /// *	Has Customize
        /// </summary>
        /// <returns>false (no customize)</returns>
        private bool HasCustomize()
        {
            return false;	//	for now
        }

        /// <summary>
        /// Save Selection Settings for PriceList
        /// </summary>
        private void SaveSelectionDetail()
        {
            Context ctx = Utility.Envs.GetContext();
            //  publish for Callout to read
            int? ID = GetSelectedRowKey();
            ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Product_ID", ID == null ? "0" : ID.ToString());
            KeyNamePair kn = (KeyNamePair)cmbPickPriceList.SelectedItem;
            ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_PriceList_Version_ID", kn.GetID());
            kn = (KeyNamePair)cmbPickWarehouse.SelectedItem;
            ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Warehouse_ID", kn.GetID());
            //
            if (_M_AttributeSetInstance_ID == -1)	//	not selected
            {
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_AttributeSetInstance_ID", "0");
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Locator_ID", "0");
            }
            else
            {
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_AttributeSetInstance_ID",
                    _M_AttributeSetInstance_ID.ToString());
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Locator_ID",
                    _M_Locator_ID.ToString());
            }
        }

        /// <summary>
        /// System has Unforfirmed records
        /// </summary>
        /// <returns>true if unconfirmed</returns>
        private bool IsUnconfirmed()
        {
            int no = Utility.Util.GetValueOfInt(VAdvantage.DataBase.DB.ExecuteScalar("SELECT COUNT(*) FROM M_InOutLineConfirm WHERE AD_Client_ID=" + Envs.GetContext().GetAD_Client_ID().ToString()));
            if (no > 0)
                return true;
            no = Utility.Util.GetValueOfInt(VAdvantage.SqlExec.ExecuteQuery.ExecuteScalar("SELECT COUNT(*) FROM M_MovementLineConfirm WHERE AD_Client_ID=" + Envs.GetContext().GetAD_Client_ID()));
            return no > 0;
        }

        /// <summary>
        /// Get Product Layout
        /// </summary>
        /// <returns>array of Column_Info</returns>
        protected override Info_Column[] GetInfoColumns()
        {
            if (s_productLayout != null)
                return s_productLayout;
            //
            s_headerPriceList = Msg.Translate(Envs.GetContext(), "M_PriceList_Version_ID");
            s_headerWarehouse = Msg.Translate(Envs.GetContext(), "M_Warehouse_ID");
            //  Euro 13
            MClient client = MClient.Get(Envs.GetContext());
            if ("FRIE".Equals(client.GetValue()))
            {
                Info_Column[] frieLayout =
            {
				new Info_Column(Msg.Translate(Envs.GetContext(),"M_Product_ID"), "p.M_Product_ID",typeof(IDColumn)).Seq(10),
				new Info_Column(Msg.Translate(Envs.GetContext(), "Name"), "p.Name", typeof(String),true,false,null).Seq(20),
                new Info_Column("QTYENTERED", "0 as QTYENTERED" , typeof(Decimal), false, false, "").Seq(30), 
				new Info_Column(Msg.Translate(Envs.GetContext(), "QtyAvailable"), 
					"bomQtyAvailable(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyAvailable", typeof(Double), true, true, null).Seq(40),
				new Info_Column(s_headerPriceList, "plv.Name", typeof(String)).Seq(50),
                new Info_Column(s_headerWarehouse, "w.Name", typeof(String)).Seq(60),
				new Info_Column(Msg.Translate(Envs.GetContext(), "PriceList"), 
					"bomPriceList(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceList",  typeof(Decimal)).Seq(70),
				new Info_Column(Msg.Translate(Envs.GetContext(), "PriceStd"), 
					"bomPriceStd(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceStd", typeof(Decimal)).Seq(80),
				new Info_Column("Einzel MWSt", 
					"pr.PriceStd * 1.19", typeof(Decimal)).Seq(90),
				new Info_Column("Einzel kompl", 
					"(pr.PriceStd+13) * 1.19", typeof(Decimal)).Seq(100),
				new Info_Column("Satz kompl", 
					"((pr.PriceStd+13) * 1.19) * 4", typeof(Decimal)).Seq(110),
				new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOnHand"), 
					"bomQtyOnHand(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyOnHand", typeof(Double)).Seq(120),
				new Info_Column(Msg.Translate(Envs.GetContext(), "QtyReserved"), 
					"bomQtyReserved(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyReserved", typeof(Double)).Seq(130),
				new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOrdered"), 
					"bomQtyOrdered(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyOrdered", typeof(Double)).Seq(140),
				new Info_Column(Msg.Translate(Envs.GetContext(), "Discontinued").Substring(0, 1), 
					"p.Discontinued", typeof(Boolean)).Seq(150),
				new Info_Column(Msg.Translate(Envs.GetContext(), "SalesMargin"), 
					"bomPriceStd(p.M_Product_ID, pr.M_PriceList_Version_ID)-bomPriceLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS Margin", typeof(Decimal)).Seq(160),
				new Info_Column(Msg.Translate(Envs.GetContext(), "PriceLimit"), 
					"bomPriceLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceLimit", typeof(Decimal)).Seq(170),
				new Info_Column(Msg.Translate(Envs.GetContext(), "IsInstanceAttribute"), 
					"pa.IsInstanceAttribute", typeof(Boolean)).Seq(180)
                    //new Info_Column(Msg.Translate(Envs.GetContext(), "Quantity"), "0 as Quantity" , typeof(Boolean)).Seq(180) 
                   
			};
                INDEX_NAME = 1;
                INDEX_PATTRIBUTE = frieLayout.Length - 1;	//	last item
                s_productLayout = frieLayout;
                return s_productLayout;
            }
            if (s_productLayout == null)
            {
                List<Info_Column> list = new List<Info_Column>();
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "M_Product_ID"), "p.M_Product_ID", typeof(IDColumn)).Seq(10));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "SelectProduct"),
                   "'N'", typeof(Boolean)).Seq(20));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "Discontinued").Substring(0, 1),
                    "p.Discontinued", typeof(Boolean)).Seq(30));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "Value"),
                    "p.Value", typeof(String)).Seq(40));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "Name"),
                    "p.Name", typeof(String), true, false, null).Seq(50));
                list.Add(new Info_Column("QTYENTERED",
                  "0 AS QTYENTERED",
                  typeof(Decimal), false, true, null).Seq(60));

                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyAvailable"),
                    "bomQtyAvailable(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyAvailable",
                    typeof(Double), true, true, null).Seq(70));
                list.Add(new Info_Column(s_headerPriceList,
                    "plv.Name", typeof(String)).Seq(80));
                list.Add(new Info_Column(s_headerWarehouse,
                   "w.Name", typeof(String)).Seq(90));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "PriceList"),
                    "bomPriceList(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceList",
                    typeof(Decimal)).Seq(100));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "PriceStd"),
                    "bomPriceStd(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceStd",
                    typeof(Decimal)).Seq(110));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOnHand"),
                    "bomQtyOnHand(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyOnHand",
                    typeof(Double)).Seq(120));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyReserved"),
                    "bomQtyReserved(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyReserved",
                    typeof(Double)).Seq(130));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOrdered"),
                    "bomQtyOrdered(p.M_Product_ID,w.M_Warehouse_ID,0) AS QtyOrdered",
                    typeof(Double)).Seq(140));
                if (isConferm) //IsUnconfirmed())
                {
                    list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyUnconfirmed"),
                        "(SELECT SUM(c.TargetQty) FROM M_InOutLineConfirm c INNER JOIN M_InOutLine il ON (c.M_InOutLine_ID=il.M_InOutLine_ID) INNER JOIN M_InOut i ON (il.M_InOut_ID=i.M_InOut_ID) WHERE c.Processed='N' AND i.M_Warehouse_ID=w.M_Warehouse_ID AND il.M_Product_ID=p.M_Product_ID) AS QtyUnconfirmed",
                        typeof(Double)).Seq(150));
                    list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "QtyUnconfirmedMove"),
                        "(SELECT SUM(c.TargetQty) FROM M_MovementLineConfirm c INNER JOIN M_MovementLine ml ON (c.M_MovementLine_ID=ml.M_MovementLine_ID) INNER JOIN M_Locator l ON (ml.M_LocatorTo_ID=l.M_Locator_ID) WHERE c.Processed='N' AND l.M_Warehouse_ID=w.M_Warehouse_ID AND ml.M_Product_ID=p.M_Product_ID) AS QtyUnconfirmedMove",
                        typeof(Double)).Seq(160));
                }
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "SalesMargin"),
                    "bomPriceStd(p.M_Product_ID, pr.M_PriceList_Version_ID)-bomPriceLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS Margin",
                    typeof(Decimal)).Seq(170));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "PriceLimit"),
                    "bomPriceLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceLimit",
                    typeof(Decimal)).Seq(180));
                list.Add(new Info_Column(Msg.Translate(Envs.GetContext(), "IsInstanceAttribute"),
                    "pa.IsInstanceAttribute",
                    typeof(Boolean)).Seq(190));

                s_productLayout = new Info_Column[list.Count];
                s_productLayout = list.ToArray();
                INDEX_NAME = 3;
                INDEX_PATTRIBUTE = s_productLayout.Length - 1;	//	last item
            }
            return s_productLayout;
        }
        Object cmblisObj, cmbwerobj;
        private void KeyEvents(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                cmblisObj = cmbPickPriceList.SelectedItem;
                cmbwerobj = cmbPickWarehouse.SelectedItem;
                ExecuteQuery();
            }
            else if (e.Key == Key.Down)
            {
                vdgvRecords.Focus();
            }
        }

        public override void Init()
        {
            InitializeComponent();
            base.outerPanel.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }


        protected override void bRefresh_Click(object sender, RoutedEventArgs e)//: base.VRefresh_Click(object sender, EventArgs e)
        {

            viewProd = false;
            if(_keyColumn.ToUpper() == "M_PRODUCT_ID" && _multiSelection && !updating)
            {
                bClose.Visibility = Visibility.Visible;
            }
            vdgvRecords.Visibility = Visibility.Visible;
            vdgvRecords2.Visibility = Visibility.Collapsed;
            txtName.Focus();
            //base.VRefresh_Click(sender,e);
            cmblisObj = cmbPickPriceList.SelectedItem;
            cmbwerobj = cmbPickWarehouse.SelectedItem;
            ExecuteQuery();
        }



        void vdgvRecords_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            foreach (DataGridColumn col in vdgvRecords.Columns)
            {
                if (col.DisplayIndex == 0 || col.DisplayIndex == 1)
                {
                    col.Visibility = Visibility.Collapsed;
                }
                //if (col is DataGridCheckBoxColumn)
                //{
                //    ((DataGridCheckBoxColumn)col).IsThreeState = false;
                //}
                //if (col.DisplayIndex = 1)
                //{
                //    col.IsReadOnly = true;
                //}
            }
        }
    }
}
